package com.csc531.lists;

import java.text.ParseException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.csc531.Manager;
import com.csc531.R;
import com.csc531.DataTypes.Task;
import com.csc531.adapters.ManagerDbAdapter;
import com.csc531.adapters.TaskListAdapter;
import com.csc531.edit.TasksEdit;
import com.csc531.settingsPanel.Settings;


/**
 * @author Javier Figueroa
 *
 */

public class TaskListByUpcoming extends ListActivity 
{
	//logging
	private static final String TAG = "CLASSES TAB";

	//activity results
	public static final int ACTIVITY_CREATE=0;
	public static final int ACTIVITY_EDIT=1;

	//menu
	private static final int INSERT_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
	private static final int DELETE_ID = Menu.FIRST + 2;
	private static final int SWITCH_TO_FATLIST = Menu.FIRST + 3;
	private static final int SETTINGS = Menu.FIRST + 4;

	private ArrayList<Integer> _tasksDatabaseRowIds;
	private ManagerDbAdapter _mDbHelper;
	private TaskListAdapter _classesTabAdapter;
	private SimpleCursorAdapter _simpleTaskCursor;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		super.onActivityResult(requestCode, resultCode, intent);
		fillTaskListData();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		((TaskListAdapter)getListAdapter()).toggle(position);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, SWITCH_TO_FATLIST, 0, R.string.menu_switch_to_fatlist);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert);
		menu.add(0, EDIT_ID, 0, R.string.menu_edit);
		menu.add(0, DELETE_ID, 0,  R.string.menu_delete);
		menu.add(0, SETTINGS, 0, R.string.menu_config);

		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch(item.getItemId()) 
		{
		case INSERT_ID:
			createTask();
			return true;
		case EDIT_ID:
			editTask();
			return true;
		case DELETE_ID:
			deleteTask();
			fillTaskListData();
			return true;
		case SWITCH_TO_FATLIST:
			switchToViewByClass();
			return true;
		case SETTINGS:
			settings();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void settings() 
	{
		Intent i = new Intent(this, Settings.class);
		startActivity(i);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		_mDbHelper = new ManagerDbAdapter(this);
		_mDbHelper.open();
		fillTaskListData();
	}

	private void fillTaskListData() 
	{
		initializeListAdapterAndRowIds();
		fetchTasksFromDatabase();

		try
		{
			populateTasksTab();
			sortTasksAndSetExpandedProperty();
		}
		catch(RuntimeException ex)
		{
			Log.v(TAG, ex.toString());
		}
		catch(ParseException ex)
		{
			Log.v(TAG, ex.toString());
		}

		setTaskListAdapter();
	}

	private void initializeListAdapterAndRowIds()
	{
		_classesTabAdapter = new TaskListAdapter(this);
		_tasksDatabaseRowIds = new ArrayList<Integer>();
	}

	private void fetchTasksFromDatabase()
	{
		Cursor taskCursor = _mDbHelper.fetchAllTasks();
		startManagingCursor(taskCursor);

		String[] from = new String[]{ManagerDbAdapter.KEY_TITLE};
		int[] to = new int[]{R.id.text1};

		_simpleTaskCursor = new SimpleCursorAdapter(this, R.layout.notes_row, taskCursor, from, to);
	}

	private void populateTasksTab() throws RuntimeException
	{
		_simpleTaskCursor.getCursor().moveToFirst();

		int numberOfRows = _simpleTaskCursor.getCursor().getCount();
		int numberOfColumns = _simpleTaskCursor.getCursor().getColumnCount();

		Log.v(TAG, "num of rows: "+numberOfRows);
		Log.v(TAG, "num of cols: "+numberOfColumns);

		for( int i = 0; i < numberOfRows ; i++ )
		{
			addTasksToTaskList();
			_simpleTaskCursor.getCursor().moveToNext();
		}
	}

	private void sortTasksAndSetExpandedProperty() throws ParseException
	{
		_classesTabAdapter.sortTasksByDate();
		_classesTabAdapter.setExpandedPropertyOnList();
	}

	private void setTaskListAdapter()
	{
		setListAdapter(_classesTabAdapter);
	}

	private void addTasksToTaskList() 
	{
		int k = 0;

		String rowId = _simpleTaskCursor.getCursor().getString(k++);
		_tasksDatabaseRowIds.add(Integer.parseInt(rowId));

		String courseName = _simpleTaskCursor.getCursor().getString(k++);
		Task task = new Task();
		task.setCourseName(courseName);

		String title = _simpleTaskCursor.getCursor().getString(k++);

		String dueDate = _simpleTaskCursor.getCursor().getString(k++);
		task.setDate(dueDate);

		task.setTitle(
				title +
				" - (" + task.getCourseName() + ")" +
				" - " + task.getDate()
		);

		String description = _simpleTaskCursor.getCursor().getString(k++);
		task.setDescription(description);

		_classesTabAdapter.addTask(task);
	}

	private void switchToViewByClass()
	{
		Intent i = new Intent(this, Manager.class);
		i.putExtra("TAB", Manager.CLASSES_TAB);
		i.putExtra("CLASSESVIEWTYPE", Manager.CLASSES_FATLIST);
		startActivity(i);

	}

	private void createTask() 
	{
		Intent i = new Intent(this, TasksEdit.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	private void editTask() 
	{
		Intent i = new Intent(this, TasksEdit.class);

		if(checkTasksExist() == false) 
		{
			return;
		}

		long id = _tasksDatabaseRowIds.get((int) getSelectedItemId());
		i.putExtra(ManagerDbAdapter.KEY_ROWID,id);
		startActivityForResult(i, ACTIVITY_EDIT);
	}

	private void deleteTask() 
	{
		if(checkTasksExist() == false) 
		{
			return;
		}

		_mDbHelper.deleteTask(_tasksDatabaseRowIds.get((int) getListView().getSelectedItemId()));
	}

	private boolean checkTasksExist() 
	{
		if(_tasksDatabaseRowIds.size() <= 0) 
		{
			return false;
		}
		else 
		{
			return true;
		}
	}
}
